<template>
  <el-dialog title="设置权限" :visible="showDialogPerm" @close="hClose">
    <el-tree
      ref="tree"
      node-key="id"
      :data="permList"
      show-checkbox
      default-expand-all
      check-strictly
      :props="{label: 'name'}"
    />

    <el-button type="primary" size="mini" @click="hSave">保存</el-button>
  </el-dialog>

</template>
<script>
import { getPermissById } from '@/api/role'
import { getPermission, assignPerm } from '@/api/permission'
import { arr2tree } from '@/utils/index'
export default {
  props: {
    showDialogPerm: {
      type: Boolean,
      required: true
    },
    curId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      permList: []
    }
  },
  created() {
    // 读取全部的权限并显示
    this.loadPermission()
  },
  methods: {
    async hSave() {
      // 1. 获取用户选中的keys
      const keys = this.$refs.tree.getCheckedKeys()
      //   console.log(keys)
      // 2. 调用接口
      await assignPerm({ id: this.curId, permIds: keys })

      // 3. 关闭弹框
      this.hClose()
    },
    async getPermiss() {
      const res = await getPermissById(this.curId)

      // 数据回填
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    async loadPermission() {
      const res = await getPermission()

      // 1. 处理数据，转树
      this.permList = arr2tree(res.data, 0)
      // 2. 渲染到tree组件
    },
    hClose() {
      this.$emit('update:showDialogPerm', false)
    }
  }
}
</script>
